package cc.rengu.redp.common.utils;

import com.alibaba.excel.EasyExcel;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class EasyExcelUtil {

    public static void export(
            HttpServletResponse response,
            List list,
            String fileName) throws IOException {
        export(response, list, fileName, "sheet1");
    }

    public static void export(
            HttpServletResponse response,
            List list,
            String fileName,
            String sheetName) throws IOException {
        if (list == null || list.size() == 0) {
            return;
        }
        EasyExcel.write(getOutputStream(fileName, response), list.get(0).getClass())
                .sheet(sheetName)
                .doWrite(list);
    }

    /**
     * 导出文件时为Writer生成OutputStream.
     *
     * @param fileName 文件名
     * @param response response
     * @return ""
     */
    private static OutputStream getOutputStream(String fileName,
                                                HttpServletResponse response) throws IOException {
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setHeader("Access-Control-Expose-Headers", "File-Name");
        response.setHeader("File-Name", fileName);
        return response.getOutputStream();
    }
}
